package com.alianzamedica.controllers.tag;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.objectsearch.sqlsearch.ObjectSearch;
import org.w3c.dom.Document;

import com.alianzamedica.businessobject.Tag;
import com.alianzamedica.tools.Enviroment;
import com.alianzamedica.view.TagViewForm;

/**
 * @author Carlos
 * 
 */
public class TagSaveAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Enviroment env = Enviroment.getInstance();
		Document doc = env.getDocument();
		ObjectSearch search = new ObjectSearch(doc,
				"com.alianzamedica.connection.ConnectionImpl");
		TagViewForm tagForm = (TagViewForm) form;
		Tag tag = tagForm.getTagObject();
		Tag t = new Tag();
		t.setTag(tagForm.getTag());
		String mensaje = "";
		if (!tagExists(t)) {
			tag.setState(String.valueOf(1));
			search.insertObject(tag);
			mensaje = "el tag se ha insertado correctamente";
		} else {
			search.updateObject(tag);
			mensaje = "el tag se ha actualizado correctamente";
		}

		request.setAttribute("mensaje", mensaje);
		String linkRetorno = "/admin/tag/listTag.do";
		request.setAttribute("linkRetorno", linkRetorno);

		return mapping.findForward("success");
	}

	/**
	 * pregunta si existe el tag.
	 * 
	 * @param tag
	 *            tag a verificar.
	 * @return indicador de existencia del tag.
	 * @throws Exception
	 *             si ocurre error.
	 */
	@SuppressWarnings("unchecked")
	public boolean tagExists(Tag tag) throws Exception {
		Enviroment env = Enviroment.getInstance();
		Document doc = env.getDocument();
		ObjectSearch search = new ObjectSearch(doc,
				"com.alianzamedica.connection.ConnectionImpl");
		Iterator<Tag> iterator = search.searchObjects(tag).iterator();
		if (iterator.hasNext()) {
			return true;
		} else {
			return false;
		}
	}

}
